package com.tang.framework.config;

import com.tang.framework.component.fliter.JwtAuthenticationTokenFilter;
import com.tang.framework.component.security.LogoutSuccessHandler;
import com.tang.framework.component.security.UnauthorizedHandler;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.annotation.web.configurers.PasswordManagementConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import jakarta.annotation.Resource;

/**
 * @author tang jun liang
 * @Date 2023/2/10 13:59
 */
@SpringBootConfiguration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig implements WebMvcConfigurer {

    @Resource
    private UnauthorizedHandler unauthorizedHandler;

    @Resource
    private LogoutSuccessHandler logoutSuccessHandler;


    @Resource
    private AccessDeniedHandler accessDeniedHandler;


    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // CSRF禁用，因为不使用session
                .csrf(AbstractHttpConfigurer::disable)
                // 认证失败处理类
                .userDetailsService(userDetailsService)
                .exceptionHandling((exception) -> exception.authenticationEntryPoint(unauthorizedHandler)
                        .accessDeniedHandler(accessDeniedHandler)
                )
                // 基于token，所以不需要session
                .sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 过滤请求
                .authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests   // 对于登录login 验证码captchaImage 允许匿名访问
                        .requestMatchers("/sys/open/login",
                                "/captchaImage").permitAll()
                        .requestMatchers(
                                HttpMethod.GET,
                                "/*.html",
                                "/*/*.html",
                                "/*/*.css",
                                "/*/*.js"

                        ).permitAll()
                        .requestMatchers("/swagger-ui/*").permitAll()
                        .requestMatchers("/swagger-resources/*").permitAll()
                        .requestMatchers("/*/api-docs").permitAll()
                        .requestMatchers("/webjars/*/*").permitAll()
                        .requestMatchers("/swagger/*").permitAll()
                        .requestMatchers("/v3/api-docs/*/*").permitAll()
                        .requestMatchers("/v3/api-docs/*").permitAll()
                        .requestMatchers("/favicon.ico").permitAll()
                        .requestMatchers("/*/*.js").permitAll()
                        .requestMatchers("/*/*.css").permitAll()
                        .requestMatchers("/*/*.png").permitAll()
                        // 除上面外的所有请求全部需要鉴权认证
                        .anyRequest().authenticated())

                .headers(header -> header.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable));
        http.logout(logout -> logout.logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler));
        // 添加JWT filter
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    /**
     * 开启跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路由
        registry.addMapping("/**")
                // 设置允许跨域请求的域名------------修改此行
                .allowedOriginPatterns("*")
                // 是否允许证书（cookies）
                .allowCredentials(true)
                // 设置允许的方法
                .allowedMethods("*")
                // 跨域允许时间
                .maxAge(3600);
    }


}
